<template>
  <a-layout>
    <a-layout-header style="background-color: #ffffff">
      <a-row>
        <a-col :span="8">
          <router-link to="/">
            <a-image :width="60" :preview="false" :src=logoImg></a-image>
          </router-link>
        </a-col>
        <a-col :span="8">
          <!-- //TODO 占位 -->
        </a-col>
        <a-col :span="8">
          <a-typography-text strong>
            已有账号？
            <router-link to="/login">
              去登录
            </router-link>
          </a-typography-text>
        </a-col>
      </a-row>
    </a-layout-header>
    <div class="img_box1">
      <a-form
          class="login-form1"
          ref="formRef"
          name="custom-validation"
          :model="formState"
          :rules="rules"
          v-bind="layout"
          @finish="handleFinish"
          @validate="handleValidate"
          @finishFailed="handleFinishFailed"
      >
        <a-form-item has-feedback label="用户名" name="username">
          <a-input v-model:value="formState.username" type="text" autocomplete="off" allow-clear/>
        </a-form-item>
        <a-form-item has-feedback label="设置密码" name="password">
          <a-input v-model:value="formState.password" type="password" autocomplete="off" allow-clear/>
        </a-form-item>
        <a-form-item has-feedback label="确定密码" name="checkPass">
          <a-input v-model:value="formState.checkPass" type="password" autocomplete="off" allow-clear/>
        </a-form-item>
        <a-form-item has-feedback label="手机号" name="mobile">
          <a-input v-model:value="formState.mobile" allow-clear/>
        </a-form-item>
        <a-form-item has-feedback label="验证码" name="checkCode">
          <a-row :gutter="16">
            <a-col :span="16">
              <a-input v-model:value="formState.checkCode" allow-clear/>
            </a-col>
            <a-col :span="12" v-if="countdownVisible">
              <a-statistic-countdown
                  :value="deadline"
                  format="ss"
                  @finish="onFinish"
                  style="margin-right: 50px"
              />S 后再次发送验证码
            </a-col>
            <a-col :span="4">
              <a-button :disabled="disable" type="link" @click="sendCheckCode">发送验证码</a-button>
            </a-col>
          </a-row>

        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" html-type="submit">立即注册</a-button>
          <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-layout>
</template>

<script setup>
import logoImg from "@/assets/logo.png";
import { reactive, ref } from 'vue';
import request from "@/utils/request";
import {message} from "ant-design-vue";
import router from "@/router";

const formRef = ref();
const formState = reactive({
  username: '',
  password: '',
  checkPass: '',
  mobile: '',
  checkCode: ''
});

const validatePass = async (_rule, value) => {
  if (value === '') {
    return Promise.reject('请输入密码');
  }else if(value.length<6 || value.length > 16){
    return Promise.reject('密码必须是6~16位字符');
  }else {
    if (formState.checkPass !== '') {
      formRef.value.validateFields('checkPass');
    }
    return Promise.resolve();
  }
};
const validatePass2 = async (_rule, value) => {
  if (value === '') {
    return Promise.reject('请再次输入密码');
  } else if (value !== formState.password) {
    return Promise.reject("两次输入的密码不一致!");
  } else {
    return Promise.resolve();
  }
};

const validateUserName = async (_rule, value) => {
  if(value === ''){
    return Promise.reject('请输入用户名！');
  } else if(value.length > 16 || value.length < 2) {
    return Promise.reject('用户名必须是2~16位字符');
  } else {
    return Promise.resolve();
  }
}

const validatePhoneNumber = async (_rule, value) => {
  if(value === ''){
    return Promise.reject('请输入手机号！');
  } else if(value.length !== 11 || ! new RegExp('^[0-9]*$').test(value)) {
    return Promise.reject('请输入正确的手机号');
  } else {
    return Promise.resolve();
  }
}

const validateCheckCode = async (_rule, value) => {
  if(value === ''){
    return Promise.reject('请输入验证码！');
  } else {
    return Promise.resolve();
  }
}

const rules = {
  checkCode:[{
    require: true,
    validator: validateCheckCode,
    trigger: 'change',
  }],
  username:[
    {
      require: true,
      validator: validateUserName,
      trigger: 'change',
    }
  ],
  password: [
    {
      required: true,
      validator: validatePass,
      trigger: 'change',
    },
  ],
  checkPass: [
    {
      validator: validatePass2,
      trigger: 'change',
    },
  ],
  mobile: [
    {
      validator: validatePhoneNumber,
      trigger: 'change'
    }
  ]
};

const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 14,
  },
};
const handleFinishFailed = errors => {
  console.log(errors);
};
const resetForm = () => {
  formRef.value.resetFields();
};
const handleValidate = (...args) => {
  console.log(args);
};

let countdownVisible = ref(false)
let disable = ref(false)

function sendCheckCode(){
  console.log('发送验证码')
  if(formState.mobile === ''){
    message.info("请输入手机号")
    return
  }
  disable.value = true
  request({
    url: `/auth/register/get-checkcode/${formState.mobile}`,
    method: 'get'
  }).then(res => {
    console.log(res)
    if(res.code === 0){
      message.success("发送验证码成功！")
      deadline = Date.now() + 1000 * 60;
      countdownVisible.value = true
    }else {
      message.info("发送验证码失败~~！"+res.msg)
      disable.value = false
    }
  }).catch(err=>{
    console.log("发送验证码失败！", err.message)
    message.error("发送验证码失败！"+err.message)
    disable.value = false
  }).finally(_=>{

  })
}

const onFinish = () => {
  console.log('倒计时完成');
  countdownVisible.value = false
  disable.value = false
};

const handleFinish = values => {
  request({
    url: '/auth/register/submit',
    method: 'post',
    data: request.adornData(values, false)
  }).then(res => {
    console.log('提交注册表单的响应', res)
    if(res.code === 0){
      message.success("注册成功")
      //跳转到登录界面
      router.push({
        path: '/login'
      })
    } else {
      message.info(res.msg)
    }
  }).catch(err=>{
    message.error("提交注册请求异常--"+err.message)
    console.log('提交注册请求异常--', err.message)
  })
};



let deadline = Date.now() + 1000 * 60;


</script>

<style>
.img_box1{
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('@/assets/loginbackground.jpg') fixed no-repeat;
  background-size: cover;
  width: 101%;
  height: 700px;
}

.login-form1 {
  width: 550px;
  height: 600px;
  display: flex;
  flex-direction: column;
  padding: 40px;
  text-align: center;
  position: relative;
  z-index: 100;
  background: inherit;
  border-radius: 18px;
  overflow: hidden; /* 隐藏多余的模糊效果 */
}

.login-form1::before {
  content: "";
  width: calc(100% + 20px);
  height: calc(100% + 20px);
  position: absolute;
  top: -10px;
  left: -10px;
  overflow: hidden;
  background: inherit;
  box-shadow: inset 0 0 0 200px rgba(255, 255, 255, 0.25);
  filter: blur(6px);
  z-index: -1;
}

.login-form1 h2 {
  font-size: 18px;
  font-weight: 400;
  color: #3d5245;
}

.login-form1 input,
.login-form1 button {
  margin: 6px 0;
  height: 36px;
  border: none;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  padding: 0 14px;
  color: #3d5245;
}

.login-form1 input::placeholder {
  color: #3d5245;
}

/* 补充，取消选中高亮蓝框 */
.login-form1 button:focus,
.login-form1 input:focus {
  outline: 0;
}

.login-form1 button {
  margin-top: 24px;
  background-color: rgba(57, 88, 69, 0.4);
  color: white;
  position: relative;
  overflow: hidden;
  cursor: pointer;
  transition: 0.4s;
}

.login-form1 button:hover {
  background-color: rgba(12, 80, 38, 0.67);
}

.login-form1 button:focus {
  outline: 0;
}

.login-form1 button::before,
.login-form1 button::after {
  content: "";
  display: block;
  width: 80px;
  height: 100%;
  background: rgba(179, 255, 210, 0.5);
  opacity: 0.5;
  position: absolute;
  top: 0;
  left: 0;
  transform: skewX(-15deg);
  filter: blur(30px);
  overflow: hidden;
  transform: translateX(-100px);
}

.login-form1 button::after {
  width: 40px;
  background: rgba(179, 255, 210, 0.3);
  left: 60px;
  opacity: 0;
  filter: blur(5px);
}

.login-form1 button:hover::before {
  transition: 1s;
  transform: translateX(320px);
  opacity: 0.7;
}

.login-form1 button:hover::after {
  transition: 1s;
  transform: translateX(320px);
  opacity: 1;
}
</style>